<?php


namespace App\Services\Jobposition;


use App\Exceptions\ApiExceptions;
use App\Models\CompanyModel;
use App\Models\JobPositionContactDingtalkModel;
use App\Models\JobPositionContactPhoneModel;
use App\Models\JobPositionContactQqModel;
use App\Models\JobPositionContactWechatModel;
use App\Models\JobpositionModel;
use App\Models\MessageModel;
use App\Models\SignUpJobpositionModel;
use App\Models\User;
use App\Services\AbstractBaseService;
use App\Services\Easemob\EasemobService;
use App\Services\Registration\RegistrationService;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;


class SignUpService extends AbstractBaseService
{
    public function list(int $user_id)
    {
        return SignUpJobpositionModel::query()->where('user_id', $user_id)->orderByDesc('id')->paginate();
    }

    public function detail(int $user_id, int $id)
    {
        $res = SignUpJobpositionModel::query()->where('user_id', $user_id)->where('job_position_id', $id)->first();
        if (!$res) {
            throw new ApiExceptions('找不到数据');
        }
        $res->message = MessageModel::query()->where('user_id', $user_id)->where('job_position_id', $id)->get();
        return $res;
    }

    /**
     * 用户获取联系方式
     * @param int $user_id
     * @param int $id
     * @return void
     * @throws ApiExceptions
     */
    public function getContact(int $user_id, int $id)
    {
        $res = SignUpJobpositionModel::query()->where('user_id', $user_id)->where('job_position_id', $id)->first();
        if (!$res) {
            throw new ApiExceptions('找不到数据');
        }
        $res->update(['is_get_contact' => 1]);
    }


    /**
     * 报名岗位
     * @param int $id
     * @param Authenticatable|User $user
     * @return Builder|Builder[]|Collection|Model|object|null
     * @throws ApiExceptions
     */
    public function signUp(int $id, Authenticatable|User $user)
    {
        if (!$user->name) {
            throw new ApiExceptions('请完善简历信息');
        }
        $cacheKey = "sign-up-jobposition-stacks-{$user->id}";
//        $info = JobpositionModel::query()
//            ->find($id);
        $info = JobpositionModel::query()->validPositions()->find($id);
        if (!$info) {
            throw new ApiExceptions('该职位不存在或已下线');
        }
        $info->checkAvailability($user);
        if (!$info) {
            throw new ApiExceptions('该职位不存在或已下线');
        }
        $lock = Cache::lock($cacheKey, 10);
        if (!$lock->get()) {
            return;
        }
//         判断是否报名过
        $doesntExist = SignUpJobpositionModel::query()->where([
            ['user_id', $user->id],
            ['job_position_id', $id],
        ])->doesntExist();
 
        if ($doesntExist) {
            DB::transaction(function () use ($info, $lock, $id, $user) {
                //减少岗位数量，增加报名人数
                $contact = $this->getJobContact(
                    jobId: $info->id,
                    contact_type: $info->contact_type,
                    contact_genre: $info->contact_genre,
                );
                if (!$contact) {
                    $info->update([
                        'cur_status' => JobpositionModel::STATUS_OFF_LINE
                    ]);
                    $lock->release();
                    throw new ApiExceptions("报名人数已满");
                }
                //设置快照信息
                if ($info->contact_type == JobpositionModel::CONTACT_MOBILE) {
                    $info->phone_number = $contact->phone_number ?? '';
                }
                if ($info->contact_type == JobpositionModel::CONTACT_QQ) {
                    $info->qq_number = $contact->qq_number ?? '';
                    $info->qq_qr_code = $contact->qq_qr_code ?? '';
                }
                if ($info->contact_type == JobpositionModel::CONTACT_WECHAT) {
                    $info->wechat_number = $contact->wechat_number ?? '';
                    $info->wechat_qr_code = $contact->wechat_qr_code ?? '';
                }
                if ($info->contact_type == JobpositionModel::CONTACT_DINGTALK) {
                    $info->dingtalk_number = $contact->dingtalk_number ?? '';
                    $info->dingtalk_qr_code = $contact->dingtalk_qr_code ?? '';
                }
                $contact->update([
                    'recruit_num' => DB::raw('`recruit_num` + 1'),
                ]);

                JobpositionModel::query()->where([
                    ['id', $id],
                ])->update([
                    'recruit_num' => DB::raw('recruit_num + 1'),
                ]);
                RegistrationService::changeRegistrationNum(
                    companyId: $info->company_id,
                    changeNum: -1,
                    operate_at: date('Y-m-d H:i:s'),
                    remark: '报名消耗'
                );
                //写入报名信息
                $signUpInfo = $info->toArray();
                unset($signUpInfo['id'], $signUpInfo['created_at'], $signUpInfo['updated_at'], $signUpInfo['deleted_at'],$signUpInfo['company']);
                $signUpInfo['job_position_id'] = $id;
                $signUpInfo['user_id'] = $user->id;
                SignUpJobpositionModel::query()->create($signUpInfo);

                //查询商家联系人，环信加好友
                $companyarr = DB::table("company")->where("id",$info->company_id)->first();
              //  $company_hx = DB::table("company_hx")->where("company_id",$info->company_id)->where("uuname",'shop_uuid_'.$info->company_id.'_'.$id)->first();
                if(empty($companyarr->uuname)){
                   // $username = 'shop_uuid_'.$info->company_id.'_'.$id;
                    $username = 'shop_uuid_'.$info->company_id;
               
                    //注册环信 获取商户用户uuid
                    $EasemobService = new EasemobService;
                    $res = $EasemobService->createUser($username,"123456",$username);
                    if(!empty($companyarr->contact_person_avatar)){
                        $contact_person_avatar = $companyarr->contact_person_avatar;
                    }else{
                        $contact_person_avatar = CompanyModel::DEFAULT_CONTACT_PERSON;
                    }
                    if(empty($companyarr->contact_person_name)){
                        $contact_person_name = $info->company_id;
                    }else{
                        $contact_person_name = $companyarr->contact_person_name;
                    }
                 
                    //设置环信用户属性 头像  昵称
                    $EasemobService->attribute($username,["avatarurl"=>$contact_person_avatar]);
                    $EasemobService->attribute($username,["nickname"=>$contact_person_name]);
                    DB::table("company")->where("id",$info->company_id)->update(["uuid"=>$res["uuid"],"uuname"=>$username]);
                   
                }else{
                    $username = $companyarr->uuname;
                }
                //添加好友
                $EasemobService = new EasemobService;
                $user = DB::table("user")->where("id",$user->id)->first();
                if(empty($user->uuname)){
                    $user_username = 'user_uuid_'.$user->id;
                    //注册环信 获取用户uuid
                    $EasemobService = new EasemobService;
                    $res = $EasemobService->createUser($user_username,"123456",$user_username);
                
                    $avatar_url = "http://oss.charityzimi.cn/head_pic/epn87GOArZ2B9mYC5YWLJ44OmTrfjPkGN8vAZCmg.png";
                    if(empty($user->name)){
                        $user_name = $user->id;
                    }else{
                        $user_name = $user->name;
                    }
                    //设置环信用户属性  头像  昵称
                    $EasemobService->attribute($user_username,["avatarurl"=>$avatar_url]);
                    $EasemobService->attribute($user_username,["nickname"=>$user_name]);

                    User::query()->where("id",$user->id)->update(["uuid"=>$res["uuid"],"uuname"=>$user_username]);
                }else{
                    $user_username = $user->uuname;
                }
               $EasemobService->add($user_username,$username);
               
            });
        } else {
            $info = SignUpJobpositionModel::query()->where('user_id', $user->id)->where('job_position_id', $id)->first();
            $info->message = MessageModel::query()->where('user_id', $user->id)->where('job_position_id', $id)->get();
        }
        $lock->release();
        //返回岗位信息
        return $info;
    }

    /**
     * 返回该职位的联系信息
     * @param int $jobId
     * @param int $contact_type
     * @param int $contact_genre
     * @return object|bool
     */
    public function getJobContact(int $jobId, int $contact_type, int $contact_genre): object|bool
    {
        $query = '';
        if ($contact_type == JobpositionModel::CONTACT_MOBILE) {
            $query = JobPositionContactPhoneModel::query();
        }
        if ($contact_type == JobpositionModel::CONTACT_QQ) {
            $query = JobPositionContactQqModel::query();
        }
        if ($contact_type == JobpositionModel::CONTACT_WECHAT) {
            $query = JobPositionContactWechatModel::query();
        }
        if ($contact_type == JobpositionModel::CONTACT_DINGTALK) {
            $query = JobPositionContactDingtalkModel::query();
        }
        if (!$query) return false;
        if ($contact_genre == JobpositionModel::CONTACT_GENRE_ORDER) {
            return $query->where('job_position_id', $jobId)->whereRaw('`number`>`recruit_num`')->first() ?? false;
        } else if ($contact_genre == JobpositionModel::CONTACT_GENRE_RAND) {
            $list = $query->where('job_position_id', $jobId)->whereRaw('`number`>`recruit_num`')->get();
            if ($list->isEmpty()) return false;
            return $list->random();
        }
        return false;
    }
}
